<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Lang;
use think\Loader;
use think\Response;
use app\common\library\Upload;
use app\common\exception\UploadException;
use think\Db;
use think\Config;
/**
 * Ajax异步请求接口
 * @internal
 */
class Ajax extends Frontend
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $layout = '';

    /**
     * 加载语言包
     */
    public function lang()
    {
        $this->request->get(['callback' => 'define']);
        $header = ['Content-Type' => 'application/javascript'];
        if (!config('app_debug')) {
            $offset = 30 * 60 * 60 * 24; // 缓存一个月
            $header['Cache-Control'] = 'public';
            $header['Pragma'] = 'cache';
            $header['Expires'] = gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
        }

        $controllername = $this->request->get('controllername');
        $lang = $this->request->get('lang');
        if (!$lang || !in_array($lang, config('allow_lang_list')) || !$controllername || !preg_match("/^[a-z0-9_\.]+$/i", $controllername)) {
            return jsonp(['errmsg' => '参数错误'], 200, [], ['json_encode_param' => JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE]);
        }

        $controllername = input("controllername");
        $className = Loader::parseClass($this->request->module(), 'controller', $controllername, false);

        //存在对应的类才加载
        if (class_exists($className)) {
            $this->loadlang($controllername);
        }

        //强制输出JSON Object
        return jsonp(Lang::get(), 200, $header, ['json_encode_param' => JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE]);
    }

    /**
     * 生成后缀图标
     */
    public function icon()
    {
        $suffix = $this->request->request("suffix");
        $suffix = $suffix ? $suffix : "FILE";
        $data = build_suffix_image($suffix);
        $header = ['Content-Type' => 'image/svg+xml'];
        $offset = 30 * 60 * 60 * 24; // 缓存一个月
        $header['Cache-Control'] = 'public';
        $header['Pragma'] = 'cache';
        $header['Expires'] = gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
        $response = Response::create($data, '', 200, $header);
        return $response;
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            return json([
                'msg'=>'上传成功',
                'code'=>1,
                'data'=>[
                    'url' => $attachment->url,
                     'fullurl' => cdnurl($attachment->url, true)
                ]
            ]);
        }
    }

    /**
     * 操作成功返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为1
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }
    public function userlevel(){
        if($this->request->isAjax()){
            $level = Db::name('UserLevel')->select();
            return json(['code'=>$level?200:0,'data'=>$level]);
        }
    }
    public function auth(){
        if($this->request->isAjax()){
            $user = $this->auth->getUser();
            if($user){
                $user['group_id'] = $user['group_id']?explode(',',$user['group_id']):[];
            }
            return json(['code'=>$user?200:0,'data'=>$user?:[]]);
        }
    }
    public function resourcetype(){
        if($this->request->isAjax()){
            $type_id = $this->request->post('type_id',1);
            $item = Db::name('ResourceItem')->where('type_id',$type_id)->order('id asc')->select();
   
        foreach ($item as $key => $value) {
            $arr = explode(',', $value['content']);
            $arr = array_merge(['全部'],$arr);
            $item[$key]['item'] = $arr;
        }
            return json(['code'=>200,'data'=>$item]);
        }
    }
    public function resource(){
        if($this->request->isAjax()){
            $list = Db::name('UserResource')->where('status','normal')->field('id,name')->select();
            return json(['code'=>200,'data'=>$list]);
        }
    }
    public function adviser(){
        if($this->request->isAjax()){
            $list = Db::name('Adviser')->where('status','normal')->order('year desc,month desc')->group('year,month')->field('year,month')->select();
            $data = [];
            foreach ($list as $key => $value) {
                if(count($data)==0){
                    $data[] = ['id'=>$value['year'],'value'=>$value['year'].'年','child'=>[['id'=>$value['month'],'value'=>$value['month'].'月']]];
                }else{
                    $flag = true;
                    foreach ($data as $k => $v) {
                        if($v['id']==$value['year']){
                            $data[$k]['child'][] = ['id'=>$value['month'],'value'=>$value['month'].'月'];
                            $flag = false;
                        }
                    }
                    if($flag){
                        $data[] = ['id'=>$value['year'],'value'=>$value['year'].'年','child'=>[['id'=>$value['month'],'value'=>$value['month'].'月']]];
                    }
                }
            }
            return json(['code'=>200,'data'=>['data'=>$data,'year'=>$list[0]['year'],'month'=>$list[0]['month']]]);
        }
    }
    public function wptype(){
        if($this->request->isAjax()){
            $cate = Db::name('Wptype')->where('status','normal')->order('weigh desc')->field('id,name')->select();
            return json(['code'=>200,'data'=>$cate]);
        }
    }
    public function sptype(){
        if($this->request->isAjax()){
            $cate = Db::name('Sptype')->where('status','normal')->order('weigh desc')->field('id,name')->select();
            return json(['code'=>200,'data'=>$cate]);
        }
    }
    public function wpcate(){
        if($this->request->isAjax()){
            $cate = Db::name('Wpcate')->where('status','normal')->order('weigh desc')->field('id,name')->select();
            return json(['code'=>200,'data'=>$cate]);
        }
    }
    public function getcate(){

        $banner = Db::name('Category')->where('status','normal')->where('image','<>', '')->order('weigh desc')->field('id,name,url,image,is_login')->select();
        $head = Db::name('Category')->where('status','normal')->where('pid', '0')->order('weigh desc')->field('id,name,url,is_login')->select();
        return json(['code'=>200,'data'=>['banner'=>$banner,'head'=>$head]]);
    }
    public function wfcate(){
        if($this->request->isAjax()){
            $cate = Db::name('Wfcate')->where('status','normal')->order('weigh desc')->field('id,name')->select();
            return json(['code'=>200,'data'=>$cate]);
        }
    }
    public function wfuser(){
        if($this->request->isAjax()){
            $list =  Db::name('Wfdocument')->where('status','normal')->where('board',1)->group('user_id')->field("count(`id`) as 'count',user_id")
            ->order('count desc')->limit(10)->select();
            if(!empty($list)){
                foreach ($list as $key => $value) {
                    $user = Db::name('User')->where('id',$value['user_id'])->field('id,nickname,avatar')->find();
                    $list[$key]['id'] = $user['id'];
                    $list[$key]['nickname'] = $user['nickname'];
                    $list[$key]['avatar'] = $user['avatar'];
                }
            }
            return json(['code'=>200,'data'=>$list]);
        }
    }
    public function featureduser (){
        if($this->request->isAjax()){
            $cate_id = $this->request->post('cate_id',0);
            $cate = Db::name('Wdcate')->where('status','normal')->where('id',$cate_id)->find();
            $list = [];
            if($cate['pid'] == 0){
                 $where['is_featured']=1;
                 $where['wdcate_id'] = $cate_id;
                 $user =Db::name('Wdocument')->where('wdcate_id',$cate['id'])->where('is_featured',1)->order('id desc')->field('DISTINCT user_id')->limit(10)->select();
            }else{
                $map['d.is_featured'] = 1;
                $map['c.wdcate_id']  = $cate_id;
                $user = Db::name('Wdocument')->alias('d')->join('wd_wdocument_category c','d.id =c.wdocument_id ')->where($map)
                ->order('d.id desc')->limit(10)->field('DISTINCT user_id')->limit(50)->select();
            }
            if(!empty($user)){
                foreach ($user as $key => $value) {
                    $u =  Db::name('User')->where('id',$value['user_id'])->field('id,nickname,avatar')->find();
                    $u['count'] = Db::name('Document')->where('user_id',$u['id'])->where('is_featured',1)->count('id');
                    $list[] =$u;
                }
            }
            return json(['code'=>200,'data'=>$list]);
        }
        
    }
    public function wdocument(){
        if($this->request->isAjax()){
            $cate_id = $this->request->post('cate_id',0);
            $type = $this->request->post('type',0);
            $cate = Db::name('Wdcate')->where('status','normal')->where('id',$cate_id)->find();
            if($cate['pid'] == 0){
                 switch ($type) {
                    case '0':
                        $weigh = 'createtime desc';
                        break;
                    case '1':
                        $weigh = 'clicks desc';
                        break;
                    case '2':
                        $weigh = 'new_flag desc';
                        break;
                    default:
                        $weigh = 'createtime desc';
                        break;
                 }
                 $where['wdcate_id'] = $cate_id;
                 $list =Db::name('wdocument')->where($where)->order($weigh)->limit(10)->select();
            }else{
                switch ($type) {
                    case '1':
                        $weigh = 'd.createtime desc';
                        break;
                    case '1':
                        $weigh = 'd.clicks desc';
                        break;
                    case '2':
                        $weigh = 'd.new_flag desc';
                        break;
                    default:
                        $weigh = 'd.createtime desc';
                        break;
                 }
                $map['c.wdcate_id']  = $cate_id;
                $list = Db::name('Wdocument')->alias('d')->join('wd_wdocument_category c','d.id =c.wdocument_id ')->where($map)
                ->order($weigh)->limit(10)->field('d.*')->select();
            }
            return json(['code'=>200,'data'=>$list]);
        }
    }
    public function wdcate(){
        $cate = Db::name('Wdcate')->where('status','normal')->field('id,name,image,user_level_id,pid')->select();
        return json(['code'=>200,'data'=>$cate]);
    }

    public function searchlog(){
        if($this->request->isAjax()){
            $data = $this->request->post('query','');
            $res = Db::name('SearchLog')->where('status','normal')->where('name','like','%'.$data.'%')->limit(10)->field('id,name')->select();
            if(!empty($res)){
                foreach ($res as $key => &$value) {
                    $value['text'] = str_replace($data, "<span style='color:#fc8939'>{$data}</span>", $value['name']);
                }
                return  json(['code'=>200,'data'=>$res]);
            }else{
                return  json(['code'=>0,'data'=>[]]);
            }
        }
    }
}
